<template>
  <div class="min-h-screen flex items-center justify-center bg-gradient-to-br from-gray-50 via-blue-50 to-indigo-100 dark:from-dark-900 dark:via-dark-800 dark:to-indigo-900 bg-grid-light dark:bg-grid">
    <div class="max-w-md w-full space-y-8 p-8">
      <!-- Logo and title -->
      <div class="text-center">
        <div class="mx-auto  rounded-2xl flex items-center justify-center  mb-6">
          <img src="/logo.png" alt="logo" class="w-16 h-16"/>
        </div>
        <h2 class="text-3xl font-bold text-gradient mb-2">
          X-Synergy OS
        </h2>
        <p class="text-gray-400 dark:text-gray-500">
          AI驱动的智能管理系统
        </p>
      </div>

      <!-- Login form -->
      <div class="card glass-effect glass-light dark:glass-dark max-w-md mx-auto p-6">
        <form @submit.prevent="handleLogin" class="space-y-6">
          <div>
            <label for="username" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              用户名
            </label>
            <input
              id="username"
              v-model="loginForm.username"
              type="text"
              autocomplete="username"
              required
              class="input-primary"
              placeholder="请输入用户名"
              :disabled="loading"
            />
          </div>

          <div>
            <label for="password" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              密码
            </label>
            <div class="relative">
              <input
                id="password"
                v-model="loginForm.password"
                :type="showPassword ? 'text' : 'password'"
                autocomplete="current-password"
                required
                class="input-primary pr-10"
                placeholder="请输入密码"
                :disabled="loading"
              />
              <button
                type="button"
                @click="showPassword = !showPassword"
                class="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                :disabled="loading"
              >
                <EyeIcon v-if="showPassword" class="w-5 h-5" />
                <EyeSlashIcon v-else class="w-5 h-5" />
              </button>
            </div>
          </div>

          <!-- Error message -->
          <div v-if="error" class="p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
            <p class="text-sm text-red-600 dark:text-red-400">{{ error }}</p>
          </div>

          <!-- Submit button -->
          <button
            type="submit"
            :disabled="loading || !loginForm.username || !loginForm.password"
            class="w-full btn-primary relative overflow-hidden group"
          >
            <div v-if="loading" class="absolute inset-0 flex items-center justify-center">
              <div class="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
            </div>
            <span :class="{ 'opacity-0': loading }">
              登录
            </span>
          </button>
        </form>

        <!-- Demo accounts -->
        <div class="mt-8 border-t border-gray-200 dark:border-dark-700 pt-6">
          <p class="text-sm text-gray-600 dark:text-gray-400 text-center mb-4">
            演示账号
          </p>
          <div class="grid grid-cols-2 gap-3">
            <button
              v-for="account in demoAccounts"
              :key="account.username"
              @click="fillDemoAccount(account)"
              class="p-3 text-left rounded-lg border border-gray-200 dark:border-dark-600 hover:border-primary-500 dark:hover:border-primary-400 hover:bg-primary-50 dark:hover:bg-primary-900/10 transition-all duration-200"
              :disabled="loading"
            >
              <p class="text-sm font-medium text-gray-900 dark:text-gray-100">
                {{ account.role }}
              </p>
              <p class="text-xs text-gray-500 dark:text-gray-400">
                {{ account.username }}
              </p>
            </button>
          </div>
        </div>
      </div>

      <!-- Features preview -->
      <div class="grid grid-cols-1 sm:grid-cols-3 gap-4 mt-8">
        <div
          v-for="(feature, index) in features"
          :key="feature.title"
          class="text-center p-4 rounded-lg bg-white/5 dark:bg-white/5 backdrop-blur-sm border border-white/10 dark:border-white/10"
          :class="`animate-fade-in animate-delay-${(index + 1) * 100}`"
        >
          <component :is="feature.icon" class="w-8 h-8 mx-auto mb-2 text-primary-400" />
          <h3 class="text-sm font-medium text-gray-800 dark:text-gray-200 mb-1">
            {{ feature.title }}
          </h3>
          <p class="text-xs text-gray-600 dark:text-gray-400">
            {{ feature.description }}
          </p>
        </div>
      </div>

      <!-- Footer -->
      <div class="text-center">
        <p class="text-xs text-gray-500 dark:text-gray-400">
          © 2024 X-Synergy OS. 智能化企业管理的未来.
        </p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useAuthStore } from '@/store/auth'
import { useAppStore } from '@/store/app'
import { useThemeStore } from '@/store/theme'

// Icons
import {
  EyeIcon,
  EyeSlashIcon,
  ChatBubbleOvalLeftEllipsisIcon,
  ChartBarIcon,
  CpuChipIcon
} from '@heroicons/vue/24/outline'

const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()
const appStore = useAppStore()
const themeStore = useThemeStore()

// Form state
const loginForm = reactive({
  username: '',
  password: ''
})

const loading = ref(false)
const error = ref('')
const showPassword = ref(false)

// Demo accounts
const demoAccounts = [
  { username: 'xos999999', password: 'xos999999', role: '超级管理员' },
  { username: 'manager', password: '123456', role: '普通管理员' },
  { username: 'sales', password: '123456', role: '销售员' },
  { username: 'warehouse', password: '123456', role: '仓库管理员' }
]

// Features
const features = [
  {
    title: 'AI对话助手',
    description: '智能分析业务数据',
    icon: ChatBubbleOvalLeftEllipsisIcon
  },
  {
    title: '实时分析',
    description: '动态生成可视化图表',
    icon: ChartBarIcon
  },
  {
    title: 'AI驱动',
    description: '机器学习优化决策',
    icon: CpuChipIcon
  }
]

// Methods
const handleLogin = async () => {
  if (loading.value) return

  error.value = ''
  loading.value = true

  try {
    const result = await authStore.login({
      username: loginForm.username,
      password: loginForm.password
    })

    if (result.success) {
      appStore.showSuccess('登录成功')
      
      // Get redirect path
      const redirectPath = (route.query.redirect as string) || '/'
      await router.push(redirectPath)
    } else {
      error.value = result.message || '登录失败'
    }
  } catch (err: any) {
    error.value = err.response?.data?.message || '登录失败，请重试'
  } finally {
    loading.value = false
  }
}

const fillDemoAccount = (account: typeof demoAccounts[0]) => {
  if (loading.value) return
  
  loginForm.username = account.username
  loginForm.password = account.password
  error.value = ''
}

// Lifecycle
onMounted(() => {
  // Clear any previous auth errors
  authStore.clearError()
  appStore.clearError()
  
  // Set page title
  appStore.setPageTitle('登录')
  
  // Apply initial theme
  themeStore.applyTheme()
})
</script>

<style scoped>
/* Ensure animations work properly */
.animate-fade-in {
  opacity: 0;
  animation: fadeIn 0.6s ease-out forwards;
}

@keyframes fadeIn {
  to {
    opacity: 1;
  }
}

/* Additional login page specific styles */
.glow-effect {
  box-shadow: 
    0 0 20px rgba(59, 130, 246, 0.3),
    0 0 40px rgba(59, 130, 246, 0.1),
    inset 0 0 20px rgba(59, 130, 246, 0.1);
}

.dark .glow-effect {
  box-shadow: 
    0 0 20px rgba(99, 102, 241, 0.4),
    0 0 40px rgba(99, 102, 241, 0.2),
    inset 0 0 20px rgba(99, 102, 241, 0.1);
}
</style>
